package main // import "gitee.com/mogile"

import (
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"gopkg.in/ini.v1"
)

type File struct {
	Fid      uint64
	Dmid     int
	Dkey     string
	Length   int
	Classid  int
	Devcount int
}

func main() {
	db, err := gorm.Open("mysql", "mogile:mogile@/mogilefs?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		fmt.Printf("%s", err)
		panic("failed to connect database")
	}
	defer db.Close()

	db.SingularTable(true)

	// 记录运行结果
	cfg, err := ini.Load("./app.ini")
	if err != nil {
		cfg = ini.Empty()
		cfg.Section("").Key("last_id").SetValue("0")
		cfg.Section("").Key("failed_keys").SetValue("")
	}
	failedKeys := cfg.Section("").Key("failed_keys").Strings(",")
	lastId := cfg.Section("").Key("last_id").Value()

	files := []File{}
	db.Where("fid > ?", lastId).Where("classid IN (?)", []string{"2", "3", "4"}).Limit(10000).Find(&files)
	for _, file := range files {
		lastId = strconv.FormatUint(file.Fid, 10)
		if err := download(file.Dkey); err != nil {
			// 如果下载失败，则保存失败的key
			failedKeys = append(failedKeys, lastId)
		}
		fmt.Printf("%s\r\n", file.Dkey)
	}
	cfg.Section("").Key("last_id").SetValue(lastId)
	cfg.Section("").Key("failed_keys").SetValue(strings.Join(failedKeys, ","))
	cfg.SaveTo("./app.ini")
}

const fileHost = "http://file.bmmyou.com/file/"

func download(filepath string) error {
	// Get the data
	resp, err := http.Get(fileHost + filepath)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return errors.New(resp.Status)
	}
	defer resp.Body.Close()

	// Create the file
	out, err := os.Create("./files/" + filepath)
	if err != nil {
		return err
	}
	defer out.Close()

	// Write the body to file
	_, err = io.Copy(out, resp.Body)
	return err
}
